package study.springcloud.config.nacos.support.listener;

import cn.hutool.core.io.IoUtil;
import cn.hutool.setting.dialect.Props;
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.nio.charset.Charset;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * （★）@RefreshScope 和 NacosConfigManager
 * （1）使用 @RefreshScope 修饰类
 * （2）通过 NacosConfigManager 获取 ConfigService
 * （3）ConfigService 新增 Listener
 */
@RefreshScope
@Slf4j
//@Component
public class _1_NacosConfigListener {

    @Autowired
    private NacosConfigManager configManager;

    @PostConstruct
    public void init() throws Exception {
        //
        ConfigService configService = configManager.getConfigService();
        //
        String dataId = "config.properties";
        String group = "DEFAULT_GROUP";
        configService.addListener(dataId, group,
                new Listener() {
                    @Override
                    public Executor getExecutor() {
                        log.info("xxxxxxxxxxxxxxxxxx");
                        return Executors.newFixedThreadPool(1);
                    }

                    @Override
                    public void receiveConfigInfo(String configInfo) {
                        //String 转 Props
                        Props props = new Props();
                        try (ByteArrayInputStream is = IoUtil.toStream(configInfo, Charset.forName("UTF-8"));) {
                            props.load(is);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                        log.info(">>>>>>>>>> {}", props);
                    }
                });
    }
}
